<?php

namespace App\Winged\Auth\Backend\Sign;

class Sign {

    private $puk ;

    public static $instance ;

    /**
     * 公钥
     * Sign constructor.
     * @param $public_key
     */
    public function __construct( $public_key ){
        $this->puk = $this->encoedPub( $public_key ) ;
    }

    /**
     * 签名加密算法
     * @param  $data 待加密字符
     * @return 16进制字符串 ,
     */
    public function encode( $data ){
        openssl_public_encrypt($data,$panText,$this->puk,OPENSSL_PKCS1_PADDING );
        return strtoupper(bin2hex($panText)) ;
    }


    public function sign( $data ){
        $params = implode(',' ,$data) ;
        //String sign = phone + "," + pwd + "," + smcode + "," + platform + "," + random;
        $sign = $this->encode($params);
        return \GuzzleHttp\json_encode(['sign' => $sign]);
    }

    private function encoedPub( $pubKey = '' ){
        $pubKey = chunk_split($pubKey,64,"\n");
        $pem = "-----BEGIN PUBLIC KEY-----\n".$pubKey."-----END PUBLIC KEY-----\n";
        $publicKey = openssl_pkey_get_public($pem);
        return $publicKey;
    }

    public static function getInstance($public_key){
        return  self::$instance  ?? ( self::$instance = new self($public_key));
    }

}
